package com.wantup.demo03xd.part05.communication.demo;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/7/3 14:51
 * <p>
 * <p>
 * 线程间通信
 */
public class Demo2 {

    private static volatile boolean flag = false;

    public static void main(String[] args) {
        Object obj = new Object();


        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!flag) {
                    synchronized (obj) {
                        try {
                            System.out.println("flag is false");
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println("flag is true");

            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!flag) {
                    synchronized (obj) {
                        try {
                            System.out.println("flag is false");
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println("flag is true");

            }
        }).start();


        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        new Thread(() -> {
            flag = true;
            synchronized (obj) {
                //唤醒所有线程
                obj.notifyAll();
            }
        }).start();


    }


}
